import React, { useEffect } from 'react';
import { Modal } from 'antd';
import './styles/on_ring.less';
import Icon from '@/components/Icon';
import { useScreenSync } from '../Context/ScreenSyncContext';
import { useTranslation } from 'react-i18next';
import Footer from './Footer';
import store from '@/store';
import AgentService from '@/modules/Agent';

interface OnRingProps {
	callType?: string;
	visible?: boolean;
	onOK: (mode: 'video' | 'audio' | 'im') => void;
	onCancel: () => void;
	imState?: boolean;
}

const OnRing = (props: OnRingProps) => {
	const { t } = useTranslation();
	const { callType = 'audio', visible, onOK, onCancel, imState } = props;
	const { screenSyncState } = useScreenSync();
	const iconClassNames = callType === 'im' ? 'icon-widget-imhujiao icon' : callType === 'audio' ? 'icon-widget-call-tonghua icon' : 'icon-widget-video icon';

	// 停止振铃
	const stopRing = () => {
		const amsStatus = store.getState().networkStatus.amsStatus;
		if (['reconnect_failed', 'reconnecting', 'offline'].includes(amsStatus)) {
			return;
		}
		const ring = document.getElementById('on-ring-source') as HTMLAudioElement;
		ring && ring.pause();
		setTimeout(() => {
			ring && ring.pause();
		}, 1000);
	};

	// 开始振铃
	const startRing = async () => {
		const ring = document.getElementById('on-ring-source') as HTMLAudioElement;
		try {
			(await ring) && ring.play();
		} catch (error) {
			console.log(error, 'start ring error');
			setTimeout(() => {
				ring && ring.pause();
			}, 1000);
		}
	};

	useEffect(() => {
		const { configure } = AgentService;
		if (visible) {
			console.log('start ring');
			startRing();
			if (configure.pocSetting.autoAnswer) {
				setTimeout(() => {
					stopRing();
					onOK(callType === 'audio' ? 'audio' : callType === 'video' ? 'video' : 'im');
				}, 100);
			}
		} else {
			console.log('stop ring');
			stopRing();
		}
	}, [visible]);

	const getLabel = () => {
		if (imState) {
			return callType === 'video' ? t('client-request-upgrade-video') : t('client-request-upgrade-audio');
		} else {
			return callType === 'im' ? t('im-session-access') : t('client-access-session');
		}
	};

	return (
		<Modal
			open={visible}
			closable={false}
			centered={true}
			maskClosable={false}
			okText={t('answer')}
			cancelText={t('hangup')}
			destroyOnClose={true}
			width={320}
			footer={
				<Footer
					callType={callType}
					imState={imState}
					onOK={mode => {
						stopRing();
						onOK(mode);
					}}
					onCancel={onCancel}
				></Footer>
			}
			className="on-ring-container"
		>
			<div className="icon-box">
				<Icon classname={iconClassNames}></Icon>
			</div>
			<div className="text">
				<p dangerouslySetInnerHTML={{ __html: getLabel() }} />
				{screenSyncState().status === 'start' ? <p>{t('screen-sync-available')}</p> : null}
			</div>

		</Modal>
	);
};

export default OnRing;
